package com.sanq.product.controller;

import com.sanq.product.config.utils.entity.Response;
import com.sanq.product.config.utils.string.StringUtil;
import com.sanq.product.utils.File2Oss;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * com.sanq.product.controller.UploadFileController
 *
 * @author sanq.Yan
 * @date 2019/7/21
 */
@RestController
@RequestMapping("/api/file")
public class UploadFileController {

    @Resource
    private File2Oss file2Oss;
    @Value("${oss.show}")
    public String ossShow;

    @PostMapping(value = "/uploads")
    public Response uploadFileByForm(HttpServletRequest request, @RequestParam("file") MultipartFile[] file) {

        if(file != null && file.length > 0) {
            String[] fileNames = new String[file.length];
            InputStream[] ioses = new InputStream[file.length];
            for(int i = 0; i < file.length; i++) {
                fileNames[i] = file[i].getOriginalFilename();
                try {
                    ioses[i] = file[i].getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            List<String> keys = file2Oss.uploadListFileToOSS(fileNames, ioses);
            if(keys == null || keys.size() <= 0)
                return new Response().failure();

            List<String> paths = new ArrayList<>();
            for(String key : keys) {
                paths.add(file2Oss.getUrl(key));
            }
            return new Response().success(paths);
        }

        return new Response().failure();
    }

    @PostMapping(value = "/delete")
    public Response deleteFileByKey(HttpServletRequest request,@RequestBody Map<String, Object> map) {

        // https://bucket-test002.oss-cn-beijing.aliyuncs.com//2019/07/23/3D8B05264E194FA1BE61428943242BE7.jpg
        String key = map.get("key").toString();

        if(StringUtil.isEmpty(key))
            return new Response().failure();

        key = key.replace(ossShow + "/", "");

        List<String> keys = new ArrayList<String>();
        keys.add(key);

        List<String> list = file2Oss.deleteFileByOSS(keys);

        return list != null && !list.isEmpty() ? new Response().success() : new Response().failure();
    }

}
